package com.alan.camunda.boot.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import org.camunda.bpm.engine.RuntimeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private RuntimeService runtimeService;


    @GetMapping("/publish")
    public String publish(String messageName) {
        runtimeService.createMessageCorrelation(messageName)
                .correlateAll();
        return "已发送消息:" + messageName;
    }

    /**
     * 发布消息给所有匹配的实例
     * @param messageName
     * @return
     */
    @GetMapping("/publish2")
    public String publish2(String messageName) {

        runtimeService.createMessageCorrelation("msg1")
                .startMessageOnly()
                .processDefinitionId("Process_0u5irwb:1:50193410-0c0a-11ef-940b-aef6d0664147")
                .correlateAll();
        return "已发送消息:" + messageName;
    }

    /**
     * 触发消息，除非是发起的场景，否则不允许指定流程定义
     * @param messageName
     * @return
     */
     @GetMapping("/publish3")
    public String publish23(String messageName) {
        // ENGINE-13025 Cannot specify a process definition id when correlate a message, except for explicit correlation of a start message.
        runtimeService.createMessageCorrelation("gogo")
                .processDefinitionId("Process_1s3wi3k:1:cca37446-11bd-11ef-86eb-42b91552ccda")
                .correlateAll();
        return "已发送消息:" + messageName;
    }

    /**
     * 根据流程实例加节点ID发送信号
     * @param procInstId
     * @param nodeId
     * @return
     */
    @GetMapping("/signal")
    public String signal(String procInstId, String nodeId) {

        runtimeService.createExecutionQuery().processInstanceId(procInstId).activityId(nodeId).list().forEach(e -> {
            System.out.println("找到了 Execution");
            JSONObject inputVars = new JSONObject();
            inputVars.put("result", 1);
            runtimeService.signal(e.getId(), inputVars);
        });

        return "已发送信号:";
    }



}
